<?php


namespace app\common;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendBatchSmsRequest;

class Sms
{
    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient()
    {
        $config = config('aliyun.sms');
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $config['key'],
            // 您的AccessKey Secret
            "accessKeySecret" => $config['secret']
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 单发短信
     */
    public function sms($phoneNumbers = '15245016157', $captcha)
    {

        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phoneNumbers,
            "signName" => config('aliyun.sms.sign_name'),
            "templateCode" => config('aliyun.sms.template_code'),
            "templateParam" => json_encode(['code' => $captcha])
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $ret = $client->sendSms($sendSmsRequest);


        return true;
        //{"bizId":"469317552158419684^0","code":"OK","message":"OK","requestId":"9C3A2445-AD5E-5982-B17D-97894AC4D4F1"}
    }

    /**
     * 群发短信
     */
    public static function sms_batch($id = 1,$sms_code)
    {
        error_reporting(E_ALL & ~E_NOTICE);
        $person = (new SmsPerson())->where('sms_id',$id)->column('mobile');
        if(!empty($person)){
            $size = 2;
            $person = array_chunk($person,$size);


            foreach ($person as $v){
                $signNameJson = [];
                for ($i=1;$i<=count($v);$i++){
                    $signNameJson[] = '哈尔滨汽车配件城' ;
                }
                writeLog($v);
                writeLog($signNameJson);
                $client = self::createClient("LTAI5tEKtTbHFjNv4ciHjCNC", "FO3qKQrKmbqgzUyEpNgwBPhfF9XTgZ");
                $sendBatchSmsRequest = new SendBatchSmsRequest([
                    "phoneNumberJson" => json_encode($v),
                    "signNameJson" => json_encode($signNameJson),
                    "templateCode" => $sms_code
                ]);// 复制代码运行请自行打印 API 的返回值
                $ret = $client->sendBatchSms($sendBatchSmsRequest);

            }
        }


        echo 'end2';
    }
}